from flask import jsonify, request
from ..models.announcement import Announcement
from ..extensions import db
from ..utils.response import pagination, error, success
from datetime import datetime

# 创建公告
def create_announcement():
    try:
        data = request.json
        
        # 验证必填字段
        if not data.get('title') or not data.get('content') or not data.get('publisher'):
            return error('公告标题、内容和发布机构为必填字段')  
        
        # 创建公告实例
        announcement = Announcement(
            title=data['title'],
            content=data['content'],
            publisher=data['publisher'],
            # announcement_time 默认使用当前时间，也可以从请求中获取
            announcement_time=data.get('announcement_time') or datetime.utcnow()
        )
        
        db.session.add(announcement)
        db.session.commit()
        
        return success(announcement.to_dict(), '公告创建成功')  
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)

# 获取公告列表
def get_announcements(data):
    """获取公告列表，支持按发布机构筛选，支持分页"""
    try:
        # 支持按发布机构筛选
        publisher = data.get('publisher')
        
        query = Announcement.query
        
        if publisher:
            query = query.filter_by(publisher=publisher)

        # 根据标题查询
        title = data.get('title')
        if title:
            query = query.filter(Announcement.title.like(f'%{title}%'))
        
        # 根据时间查询
        start_time = data.get('announcement_time')
        if start_time:
            query = query.filter(Announcement.announcement_time >= start_time)
        
        # 计算总数
        total = query.count()
        
        # 按公告时间倒序排列，最新的排在前面
        query = query.order_by(Announcement.announcement_time.desc())
        
        # 获取分页参数
        page = int(data.get('page', 1))
        page_size = int(data.get('page_size', 10))
        
        # 处理无效的分页参数
        if page < 1:
            page = 1
        if page_size < 1:
            page_size = 10
        elif page_size > 100:
            page_size = 100  # 限制最大每页记录数
        
        # 计算偏移量
        offset = (page - 1) * page_size
        
        # 获取分页数据
        announcements = query.offset(offset).limit(page_size).all()
        
        # 返回分页数据
        return pagination(
            items=[announcement.to_dict() for announcement in announcements],
            total=total,
            msg='获取成功',
            code=200
        )
    except Exception as e:
        return error('获取失败', 500)

# 获取单个公告
def get_announcement():
    try:
        announcement_id = request.args.get('id')
        
        if not announcement_id:
            return jsonify({'error': '未提供公告ID'}), 400
        
        announcement = Announcement.query.get(announcement_id)
        
        if not announcement:
            return jsonify({'error': '公告不存在'}), 404
        
        return success(announcement.to_dict(), '获取成功')  
    except Exception as e:
        return error(str(e), 500)

# 更新公告
def update_announcement():
    try:
        data = request.json
        announcement_id = data.get('id')
        
        if not announcement_id:
            return error('未提供公告ID')            
        
        announcement = Announcement.query.get(announcement_id)
        
        if not announcement:
            return jsonify({'error': '公告不存在'}), 404
        
        # 更新字段
        if 'title' in data:
            announcement.title = data['title']
        if 'content' in data:
            announcement.content = data['content']
        if 'publisher' in data:
            announcement.publisher = data['publisher']
        if 'announcement_time' in data:
            announcement.announcement_time = data['announcement_time']
        
        db.session.commit()
        
        return success(announcement.to_dict(), '公告更新成功')  
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)

# 删除公告
def delete_announcement():
    try:
        data = request.json
        announcement_id = data.get('id')
        
        if not announcement_id:
            return error('未提供公告ID')            
        
        announcement = Announcement.query.get(announcement_id)
        
        if not announcement:
            return error('公告不存在')        
        
        db.session.delete(announcement)
        db.session.commit()
        
        return success(announcement.to_dict(), '公告删除成功')  
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)
